package JDBC;
import java.sql.*;
import javax.sql.DataSource;

public class JDBCPersonDao {

	private DataSource dataSource;
	
	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}
	
//	public void setConnection(Connection connection) {
//		this.connection = connection;
//	}
	
	//插入一条信息
	public void insert(String name,String age) {
		String sql = "insert into student" + "(name,age) values (?,?)"; //通过?来设置占位符
		Connection conn = null;
		
		
		try {
			conn = this.dataSource.getConnection();
			PreparedStatement pStatement = conn.prepareStatement(sql);
			pStatement.setString(1, name);
			pStatement.setString(2, age);
			int rs = pStatement.executeUpdate(); //执行sql语句
			if (rs >=1) {
				System.out.println("插入成功");
			}
			pStatement.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	//查找一条信息
	public void findUserByName(String name) {
		String sql = "select * from student where name = ?";
		Connection conn = null;
		PreparedStatement pstate;
		try {
			conn = this.dataSource.getConnection();
			pstate = conn.prepareStatement(sql);
			pstate.setString(1, name);
			ResultSet resut = pstate.executeQuery();
			while (resut.next()) {
				System.out.println("name:"+resut.getString("name")+"  age:"+resut.getString("age"));
			}
			
			pstate.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
}
